#encoding:utf8

"""
用户在不同的程序中间实现 互斥锁
输入全局变量obj, 会判断其lock值是否是False, 只有在False的时候才会继续执行
"""
import time

lock_sleep_time = 0.001


class SimpleLock(object):
    def __init__(self):
        self.lock = False

    def acquire(self):
        self.lock = True

    def release(self):
        self.lock = False

    @property
    def Lock(self):
        return self.lock


class WithLock(object):
    def __init__(self, lock_obj, timeout=60):
        # obj :: lock 对象
        self.lock_obj = lock_obj
        self.timeout = timeout

    def __enter__(self):
        st = time.time()
        while 1:
            if self.lock_obj.lock:
                time.sleep(lock_sleep_time)
                et = time.time()
                if (et - st) > self.timeout:
                    raise Exception("can not get lock!")
                continue
            self.lock_obj.acquire()
            break

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.lock_obj.release()


simple_lock = SimpleLock()
